package com.kcwx.common.core.page;

import com.alibaba.fastjson2.JSONObject;
import com.kcwx.common.core.text.Convert;
import com.kcwx.common.enums.HttpMethod;
import com.kcwx.common.utils.ServletUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.Objects;

/**
 * 表格数据处理
 * 
 */
public class TableSupport
{
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    public static final String PAGE_NO = "pageNo";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";

    /**
     * 分页参数合理化
     */
    public static final String REASONABLE = "reasonable";

    /**
     * 封装分页对象
     */
    public static PageDomain getPageDomain()
    {
        PageDomain pageDomain = new PageDomain();
        HttpServletRequest request = ServletUtils.getRequest();
        String method = request.getMethod();
        if (Objects.equals(HttpMethod.POST.name(),method)) {
            buildPostPage(pageDomain, request);
        } else {
            pageDomain.setPageNum(Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1));
            pageDomain.setPageSize(Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10));
        }
        pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
        pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
        pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));
        return pageDomain;
    }

    private static void buildPostPage(PageDomain pageDomain, HttpServletRequest request) {
        int pageSize = 10;
        int pageNum = 1;
        try {
            BufferedReader reader = request.getReader();
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append('\n');
            }
            String body = stringBuilder.toString();
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (!jsonObject.isEmpty()){
                pageNum = jsonObject.getInteger(PAGE_NUM);
                pageSize = jsonObject.getInteger(PAGE_SIZE);
            }

        } catch (Exception e){

        }
        pageDomain.setPageNum(Convert.toInt(pageNum, 1));
        pageDomain.setPageSize(Convert.toInt(pageSize, 10));
    }

    public static PageDomain buildPageRequest()
    {
        return getPageDomain();
    }
}
